package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.OrderDAO;
import it.unibz.ti2.internetPizzeria.entities.Order;
import it.unibz.ti2.internetPizzeria.utils.OrderUtil;
import it.unibz.ti2.internetPizzeria.utils.ServletUtil;
import it.unibz.ti2.internetPizzeria.webAttributes.OrderInfo;
import it.unibz.ti2.internetPizzeria.webAttributes.UserInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Retrieves list of all current user's orders. Separates them between current
 * and previous orders and passing as parameters to checkOrderStatus.jsp page
 * responsible for display
 */
public class CheckOrderStatus extends HttpServlet {

	private static final long serialVersionUID = 2166833099835415369L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		OrderDAO orderDAO = null;
		try {
			orderDAO = new OrderDAO();
			orderDAO.openSession();

			UserInfo userInfo = (UserInfo)request.getSession().getAttribute("userInfo");
			
			List<Order> orders = orderDAO.getOrdersForCustomer(userInfo.getId());
			List<Order> previousOrders = new ArrayList<Order>();
			List<Order> currentOrders = new ArrayList<Order>();
			for (Order order : orders) {
				if (order.getStatus().equals(Order.StatusDelivered) 
						|| order.getStatus().equals(Order.StatusNotDelivered)
						|| order.getStatus().equals(Order.StatusCancelled)){
					previousOrders.add(order);
				}
				else{
					currentOrders.add(order);
				}
			}

			List<OrderInfo> currentOrderInfos = OrderUtil.getOrderInfos(currentOrders);
			List<OrderInfo> previousOrderInfos = OrderUtil.getOrderInfos(previousOrders);
			request.setAttribute("currentOrderInfos", currentOrderInfos);
			request.setAttribute("previousOrderInfos", previousOrderInfos);
			
			ServletUtil.redirect(request, response, "/checkOrderStatus.jsp");
			
		} catch (Exception ex) {			
			ex.printStackTrace();
		} finally {
			if (orderDAO != null){
				orderDAO.closeSession();
			}
		}
	}
}
